<template>

  <!-- 字段维护 -->
  <div class="field-maintenance">
    <el-drawer
      title="字段维护"
      :visible.sync="drawer"
      :direction="direction"
      size="1100px"
      :destroy-on-close="true"
    >
      <p class="service-info"> 服务名称：{{ serviceManagerData.serviceName }}， 服务编号： {{ serviceManagerData.serviceCode }} </p>
      <el-button @click="addBtn"> 新增 </el-button>
      <span class="service-info" style="float: right">顶层字段是否为集合:<el-switch
        v-model="serviceManagerData.topIsList"
        active-text="是"
        active-value="Y"
        active-color="#87D068"
        inactive-text="否"
        inactive-value="N"
        inactive-color="#D9001B"
        @change="changeTopIsList()"
      /></span>
      <FlexTable
        ref="table"
        v-loading="loading"
        row-key="id"
        border
        lazy
        :load="load"
        :data="tableData"
        :columns="columnsOptions"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      />
    </el-drawer>

    <!-- 字段编辑 -->
    <el-drawer
      title="字段编辑"
      :visible.sync="innerDrawer"
      :direction="direction"
      size="700px"
      :destroy-on-close="true"
    >
      <el-form ref="form" :model="form" :rules="formRules" label-width="120px">
        <el-form-item label="服务名称:">
          {{ serviceManagerData.serviceName }}
        </el-form-item>
        <el-form-item label="服务编号:">
          {{ serviceManagerData.serviceCode }}
        </el-form-item>
        <el-form-item label="字段标识:" prop="field">
          <el-input v-model="form.field" clearable :maxlength="100" placeholder="请输入字段标识" />
        </el-form-item>
        <el-form-item label="父字段:" prop="parentField">
          <el-cascader
            v-model="form.parentField"
            :disabled="form.id != ''"
            clearable
            :options="tableData"
            :props="{
              checkStrictly: true,
              value: 'id',
              label: 'fieldName',
              lazy: true,
              lazyLoad: lazyLoad
            }"
          />
        </el-form-item>
        <el-form-item label="字段备注:" prop="fieldName">
          <el-input v-model="form.fieldName" clearable :maxlength="100" placeholder="请输入字段备注" />
        </el-form-item>
        <el-form-item label="字段类型:" prop="fieldType">
          <el-select v-model="form.fieldType" clearable placeholder="请选择字段类型">
            <el-option
              v-for="(item, index) in dictOptions.field_type"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否集合:" prop="isList">
          <el-select v-model="form.isList" clearable placeholder="请选择是否集合">
            <el-option
              v-for="(item, index) in dictOptions.yesOrNoStatus"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="字段长度:" prop="fieldLength">
          <el-input-number v-model="form.fieldLength" :min="0" :controls="false" />
        </el-form-item>
        <el-form-item v-if="form.fieldType == '5' || form.fieldType == '6'" label="小数位:" prop="fieldDecimal">
          <el-input-number v-model="form.fieldDecimal" :min="0" :controls="false" />
        </el-form-item>
        <el-form-item label="空值校验:">
          <el-switch
            v-model="form.checkEmpty"
            active-text="开"
            active-value="1"
            active-color="#87D068"
            inactive-text="关"
            inactive-value="2"
            inactive-color="#D9001B"
          />
        </el-form-item>
        <el-form-item label="类型、长度校验:">
          <el-switch
            v-model="form.checkTl"
            active-text="开"
            active-value="1"
            active-color="#87D068"
            inactive-text="关"
            inactive-value="2"
            inactive-color="#D9001B"
          />
        </el-form-item>
        <el-form-item label="备注:" prop="remarks">
          <el-input v-model="form.remarks" :rows="3" clearable :maxlength="100" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item>
          <el-button @click="innerDrawer = false"> 取消 </el-button>
          <el-button type="primary" :loading="!canClick" :disabled="!canClick" @click="addConfirmBtn('form')"> 确定 </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import {
  fieldTreeListApi,
  fieldAddApi,
  fieldDeleteApi, updateTopIsList
} from '@/api/serviceManage/requestPartyServiceManage'
import dictMixin from '@/utils/mixins/dict'
export default {
  mixins: [
    dictMixin(['field_type', 'yesOrNoStatus'])
  ],

  props: {
    serviceManagerData: {
      type: Object,
      default: () => {}
    }
  },

  data () {
    return {
      canClick: true,
      loading: false,
      drawer: false,
      innerDrawer: false,
      direction: 'rtl',
      tableData: [],
      columnsOptions: [
        { label: '字段标识', prop: 'field', width: 150, align: 'left', headerAlign: 'left' },
        { label: '字段备注', prop: 'fieldName' },
        { label: '字段类型',
          customRender: scope => {
            return this.getDictText('field_type', scope.row.fieldType)
          }
        },
        { label: '小数位', prop: 'fieldDecimal' },
        { label: '字段长度', prop: 'fieldLength' },
        { label: '备注', prop: 'remarks' },
        { label: '空值校验', width: 120,
          customRender: (scope) => {
            return <el-switch
              disabled
              vModel={scope.row.checkEmpty}
              active-value='1'
              active-color='#87D068'
              inactive-value='2'
            />
          }
        },
        { label: '类型、长度校验', width: 120,
          customRender: (scope) => {
            return <el-switch
              disabled
              vModel={scope.row.checkTl}
              active-value='1'
              active-color='#87D068'
              inactive-value='2'
            />
          }
        },
        { label: '父字段', prop: 'serviceCode' },
        { label: '操作', width: 120,
          customRender: (scope) => {
            return [
              <el-button type='text' onClick={() => this.updateBtn(scope.row)}> 修改 </el-button>,
              <el-button type='text' class='text-del-btn' onClick={() => this.delBtn(scope.row)}> 删除 </el-button>
            ]
          }
        }
      ],
      form: {
        field: '',
        parentId: '',
        parentField: [],
        fieldName: '',
        fieldType: '',
        isList: '2',
        fieldLength: void 0,
        fieldDecimal: void 0,
        checkEmpty: '2',
        checkTl: '2',
        remarks: ''
      },
      formRules: {
        field: { required: true, message: '请输入字段标识', trigger: 'blur' },
        // parentField: { required: true, message: '请选择父字段', trigger: 'change' },
        fieldName: { required: true, message: '请输入字段备注', trigger: 'blur' },
        fieldType: { required: true, message: '请选择字段类型', trigger: 'change' },
        isList: { required: true, message: '请选择是否集合', trigger: 'change' }
      },
      childrenData: [],
      maps: new Map()
    }
  },

  methods: {

    async initData () {
      this.drawer = true
      this.form.parentId = ''
      await this.$nextTick()
      this.getTableData()
    },

    // 级联选择器懒加载
    lazyLoad (node, resolve) {
      fieldTreeListApi({
        serviceManagerId: this.serviceManagerData.id,
        parentId: node.value
      })
        .then(({ code, data }) => {
          if (code === '00000') {
            resolve(data.map(item => {
              return {
                ...item,
                disabled: item.fieldType != '8'
              }
            }))
          }
        })
    },

    // 重新触发树形表格的load函数
    refreshLoadTree (parentId) {
      // 根据父级id取出对应节点数据
      if (!this.maps.get(parentId)) return
      const { tree, treeNode, resolve } = this.maps.get(parentId)
      this.$set(this.$refs.table.$children[0].store.states.lazyTreeNodeMap, parentId, [])

      if (tree) {
        this.load(tree, treeNode, resolve)
      }
    },

    // 懒加载表格
    load (tree, treeNode, resolve) {
      this.maps.set(tree.id, { tree, treeNode, resolve })
      this.loading = true
      fieldTreeListApi({
        serviceManagerId: this.serviceManagerData.id,
        parentId: tree.id
      })
        .then(({ code, data }) => {
          if (code === '00000') {
            resolve(data.map(item => {
              return {
                ...item,
                hasChildren: true
              }
            }))
          }
        }).finally(() => {
          this.loading = false
        })
    },

    // 新增字段确定
    addConfirmBtn (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.canClick = false
          if (this.form.parentField && this.form.parentField.length > 0) {
            this.form.parentId = this.form.parentField.at([-1])
          }

          fieldAddApi({
            serviceManagerId: this.serviceManagerData.id,
            ...this.form
          }, this.form.id).then(({ code, data }) => {
            if (code === '00000') {
              this.innerDrawer = false
              this.getTableData()
            }
          }).finally(() => {
            this.canClick = true
          })
        }
      })
    },

    // 新增按钮
    async addBtn () {
      this.innerDrawer = true
      this.form = {
        id: '',
        field: '',
        parentId: '',
        parentField: [],
        fieldName: '',
        fieldType: '',
        isList: '2',
        fieldLength: void 0,
        fieldDecimal: void 0,
        checkEmpty: '2',
        checkTl: '2',
        remarks: ''
      }
      await this.$nextTick()
      this.$refs.form.clearValidate()
    },
    // 修改顶层字段是否为集合
    changeTopIsList () {
      updateTopIsList({
        id: this.serviceManagerData.id,
        topIsList: this.serviceManagerData.topIsList
      }).then(({ code, data }) => {
        this.$message.success('修改成功')
      })
    },
    // 修改按钮
    updateBtn (row) {
      this.innerDrawer = true
      this.form = {
        id: row.id,
        field: row.field,
        parentId: row.parentId,
        parentField: row.parentField,
        fieldName: row.fieldName,
        fieldType: row.fieldType,
        isList: row.isList,
        fieldLength: row.fieldLength,
        fieldDecimal: row.fieldDecimal,
        checkEmpty: row.checkEmpty,
        checkTl: row.checkTl,
        remarks: row.remarks
      }
    },

    // 删除按钮
    delBtn (row) {
      this.form.id = row.id
      this.form.parentId = row.parentId
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        fieldDeleteApi({
          ids: row.id.split(',')
        }).then(({ code, data }) => {
          if (code === '00000') {
            this.$message.success('删除成功')
            this.getTableData()
          }
        })
      })
    },

    // 获取表格数据
    getTableData () {
      if (this.form.parentId && this.form.parentId != -1) {
        this.refreshLoadTree(this.form.parentId)
      } else {
        this.loading = true
        fieldTreeListApi({
          serviceManagerId: this.serviceManagerData.id,
          parentId: this.form.parentId
        })
          .then(({ code, data }) => {
            if (code === '00000') {
              this.tableData = data.map(item => {
                return {
                  ...item,
                  hasChildren: true,
                  disabled: item.fieldType != '8'
                }
              })
            }
          }).finally(() => {
            this.loading = false
          })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.field-maintenance {
  ::v-deep .el-drawer {

    .service-info {
      border-bottom: 1px solid #ddd;
      padding-bottom: 10px;

    }

    .el-table {
      margin-top: 20px;
    }

    .el-input .el-input__inner {
      text-align: left;
    }
  }
}

</style>
